package org.csu.mypetstore_ssm.service;

import jakarta.servlet.http.HttpSession;
import org.csu.mypetstore_ssm.domain.Cart;
import org.csu.mypetstore_ssm.domain.CartItem;
import org.csu.mypetstore_ssm.domain.Item;
import org.csu.mypetstore_ssm.domain.Order;
import org.csu.mypetstore_ssm.persistence.OrderMapper;
import org.csu.mypetstore_ssm.persistence.ProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class OrderService {
    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private OrderMapper orderMapper; // 注入 OrderMapper
    @Autowired
    private CatalogService catalogService;

    /**
     * 保存订单到数据库
     */
    public void saveOrder(Order order) {
        // 插入订单数据到 ORDERS 表
        orderMapper.insertOrder(order);

        // 插入订单状态数据到 ORDERSTATUS 表
        orderMapper.insertOrderStatus(order);
    }
    public void placeOrder(Cart cart){
        // 遍历购物车中的商品
        for (CartItem cartItem : cart.getItemList()) {
            String itemId = cartItem.getItem().getItemId();
            int quantity = cartItem.getQuantity();

            // 查询当前库存
            int currentAmount = catalogService.getInventoryQuantity(itemId);
            System.out.println(itemId + " 当前库存: " + currentAmount + ", 需要减少: " + quantity);

            // 预检查库存
            if (currentAmount < quantity) {
                throw new RuntimeException("商品 " + itemId + " 库存不足，当前库存: " + currentAmount + ", 需要数量: " + quantity);
            }
            quantity=currentAmount-quantity;
            // 减少库存
            System.out.println(itemId+"kucun"+ quantity);
            catalogService.reduceItemQuantity(itemId, quantity);
        }
        // 其他下单逻辑（例如生成订单、保存订单等）
    } // 下单

}


